package com.baidu.service;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class NettyProviderServer {
    private int port;
    public NettyProviderServer (int port){
        this.port = port;
    }

    public void runServer() throws Exception{
        // 定义事件的监听组
        NioEventLoopGroup bootGroup = new NioEventLoopGroup();
        //定义worker，用于处理已经被接受的事件
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            //定义Nio的服务启动类
            ServerBootstrap sbs = new ServerBootstrap();
            sbs.group(bootGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,128) //设置tcp最大缓存个数
                    .childOption(ChannelOption.SO_KEEPALIVE,true) //保持连接的正常状态
                    .handler(new LoggingHandler(LogLevel.INFO)) //日志
                    .childHandler(new ChannelInitializer<SocketChannel>(){ //管道配置，编码解码
                        //重写channel初始化方法
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //管道的注册channel
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast("decode",new StringDecoder()); //解码
                            pipeline.addLast("encode",new StringEncoder()); //编码
                            //处理接受到的请求数据
                            pipeline.addLast(new NettyServerHandler());
                        }
                    });
            System.out.println("--------server启动--------");

            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true){
                        try {
                            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                            String str = in.readLine();
                            if (NettyServerHandler.channelList.size()>0){
                                for (Channel channel : NettyServerHandler.channelList) {
                                    channel.writeAndFlush(str);
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }).start();

            ChannelFuture cf = sbs.bind(port).sync();
            cf.channel().closeFuture().sync();
        } finally {
            bootGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new NettyProviderServer(9911).runServer();
    }


}
